package com.hmall.item.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.constans.MqConstants;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //分页查询商品
    @GetMapping("/list")
    public PageDTO<Item> itemPage(@RequestParam("page") Integer page, @RequestParam("size") Integer size){
        Page<Item> objectPage = new Page<>(page, size);
        Page<Item> page1 = itemService.page(objectPage);

        PageDTO<Item> objectPageDTO = new PageDTO<>();
        objectPageDTO.setTotal(page1.getTotal());
        objectPageDTO.setList(page1.getRecords());
        return objectPageDTO;
    }

    @GetMapping("/{id}")
    public Item itemByID(@PathVariable("id") Long id){
        return itemService.getById(id);
    }

    //新增商品
    @PostMapping
    public void itemInsert(@RequestBody Item item){
        itemService.save(item);
    }

    //商品上架、下架
    @Transactional
    @PutMapping("/status/{id}/{status}")
    public void itemStatus(@PathVariable("id") Integer id,@PathVariable("status") Integer status){
        Item byId = itemService.getById(id);
        byId.setStatus(status);
        itemService.updateById(byId);
        if (status == 1){
            rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_INSERT_KEY,id);
        }else {
            rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_DELETE_KEY,id);
        }
    }

    //修改商品
    @PutMapping
    public void itemUpdate(@RequestBody Item item){
        itemService.updateById(item);
    }

    //删除商品
    @DeleteMapping("/{id}")
    public void itemDelete(@PathVariable("id") Integer id){
        itemService.removeById(id);
    }

}
